import os.path
import pygame.image
from settings import settings			

def load(path):
	return pygame.image.load(path).convert()

def load_alpha(path):
	return pygame.image.load(path).convert_alpha()

class Request(object):
	def __init__(self, path, loaded, loader=load_alpha, relative=True):
		self.path = path
		self.loaded = loaded
		self.loader = loader
		self.relative = relative

class GraphicsManager(object):
	def __init__(self, path=settings.paths.graphics):
		self.path = path
		self.requests = set()
		self.loadable = False
		
	def request(self, request):
		self.requests.add(request)
		
		if self.loadable:
			self.load()
	
	def load(self):
		self.loadable = True
		
		for request in self.requests:
			if request.relative:
				imagepath = os.path.join(self.path, request.path)
			else:
				imagepath = request.path
			
			image = request.loader(imagepath)
			request.loaded(image)
		
		self.requests.clear()

graphics = GraphicsManager()

def _loaded(object, attr):
	def loaded(graphic):
		setattr(object, attr, graphic)
	
	return loaded

def request_replace(*objects, **kwargs):
	attr = kwargs.get("attr", "graphic")
	manager = kwargs.get("loader", graphics)
	alpha = kwargs.get("alpha", True)
	relative = kwargs.get("relative", True)
	
	if alpha:
		loader = load_alpha
	else:
		loader = load
	
	for object in objects:
		manager.request(Request(getattr(object, attr), _loaded(object, attr), loader, relative=relative))
